import os
from alipay import AliPay
from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView

# Create your views here.
from orders.models import OrderInfo
from rest_framework.response import Response

from payments.models import Payment


class AlipayURLView(APIView):

    """
        构建支付宝跳转连接
    """

    def get(self,request,order_id):
        # 1、获取订单编号
        # 2、验证订单
        try:
            order=OrderInfo.objects.get(order_id=order_id,pay_method=2,status=1)
        except:
            return Response({'error':'订单错误'},status=400)
        # 3、生成支付对像
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'keys/app_private_key.pem'),
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'keys/alipay_public_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug = settings.ALIPAY_DEBUG  # 默认False
        )

        # 4、生成携带的查询字符串数据
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id, # 订单编号
            total_amount=str(order.total_amount),  # 订单价格
            subject='美多商城',    # 标题
            return_url="http://www.meiduo.site:8080/pay_success.html",
        )
        # 5、拼接完整的跳转链接
        alipay_url=settings.ALIPAY_URL+order_string
        # 6、返回跳转链接
        return Response({'alipay_url':alipay_url})

class AlipaySaveView(APIView):
    """
        保存支付结果
    """

    def put(self,request):
        # 1、获取支付宝返回的查询字符串
        data=request.query_params.dict()
        # 2、验证支付宝返回的查询字符串数据
        signature = data.pop("sign")

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_public_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        success = alipay.verify(data, signature)
        if success:
            # 3、验证成功 绑定交易单号和订单号
            order_id=data['out_trade_no']
            trade_id=data['trade_no']
            Payment.objects.create(order_id=order_id,trade_id=trade_id)
            # 4、更新订单状态
            OrderInfo.objects.filter(order_id=order_id).update(status=2)
            # 5、返回结果
            return Response({'trade_id':trade_id})

        else:
            return Response({'ERROR':'校验失败'},status=400)
